import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, StarOutlined, FileTextOutlined, CheckOutlined, CloseOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Tabs, Tag, Rate, Descriptions } from 'antd';

import { supplierApi } from '../../api/supplierApi';

const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

export default function SupplierManagement() {
  const [loading, setLoading] = useState(false);
  const [supplierList, setSupplierList] = useState([]);
  const [categories, setCategories] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [categoryModalVisible, setCategoryModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [editingCategory, setEditingCategory] = useState(null);
  const [form] = Form.useForm();
  const [categoryForm] = Form.useForm();

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    setLoading(true);
    try {
      const [suppliersResponse, categoriesResponse] = await Promise.all([
        supplierApi.getSupplierList(),
        supplierApi.getSupplierCategories()
      ]);
      setSupplierList(suppliersResponse.data);
      setCategories(categoriesResponse.data);
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAddSupplier = () => {
    setEditingRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEditSupplier = (record) => {
    setEditingRecord(record);
    form.setFieldsValue(record);
    setModalVisible(true);
  };

  const handleDeleteSupplier = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个供应商吗？',
      onOk: async () => {
        try {
          await supplierApi.deleteSupplier(id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmitSupplier = async (values) => {
    try {
      if (editingRecord) {
        await supplierApi.updateSupplier(editingRecord.id, values);
        message.success('更新成功');
      } else {
        await supplierApi.createSupplier(values);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchData();
    } catch (error) {
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };

  const handleAddCategory = () => {
    setEditingCategory(null);
    categoryForm.resetFields();
    setCategoryModalVisible(true);
  };

  const handleEditCategory = (record) => {
    setEditingCategory(record);
    categoryForm.setFieldsValue(record);
    setCategoryModalVisible(true);
  };

  const handleDeleteCategory = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个分类吗？',
      onOk: async () => {
        try {
          await supplierApi.deleteSupplierCategory(id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmitCategory = async (values) => {
    try {
      if (editingCategory) {
        await supplierApi.updateSupplierCategory(editingCategory.id, values);
        message.success('更新成功');
      } else {
        await supplierApi.createSupplierCategory(values);
        message.success('创建成功');
      }
      
      setCategoryModalVisible(false);
      fetchData();
    } catch (error) {
      message.error(editingCategory ? '更新失败' : '创建失败');
    }
  };

  const handleCertify = async (id) => {
    try {
      await supplierApi.certifySupplier(id, { remark: '认证通过' });
      message.success('认证成功');
      fetchData();
    } catch (error) {
      message.error('认证失败');
    }
  };

  const handleDecertify = async (id) => {
    try {
      await supplierApi.decertifySupplier(id, { remark: '取消认证' });
      message.success('取消认证成功');
      fetchData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  const supplierColumns = [
    {
      title: '供应商名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '联系人',
      dataIndex: 'contact',
      key: 'contact',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '评级',
      dataIndex: 'rating',
      key: 'rating',
      render: (rating) => <Rate disabled value={rating} />,
    },
    {
      title: '认证状态',
      dataIndex: 'certified',
      key: 'certified',
      render: (certified) => (
        <Tag color={certified ? 'green' : 'orange'}>
          {certified ? '已认证' : '未认证'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} size="small">
            查看
          </Button>
          <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEditSupplier(record)}>
            编辑
          </Button>
          <Button type="link" icon={<FileTextOutlined />} size="small">
            合同
          </Button>
          <Button type="link" icon={<StarOutlined />} size="small">
            评价
          </Button>
          {record.certified ? (
            <Button type="link" icon={<CloseOutlined />} size="small" onClick={() => handleDecertify(record.id)}>
              取消认证
            </Button>
          ) : (
            <Button type="link" icon={<CheckOutlined />} size="small" onClick={() => handleCertify(record.id)}>
              认证
            </Button>
          )}
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDeleteSupplier(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const categoryColumns = [
    {
      title: '分类名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEditCategory(record)}>
            编辑
          </Button>
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDeleteCategory(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <Tabs defaultActiveKey="suppliers">
          <TabPane tab="供应商管理" key="suppliers">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddSupplier}>
                  新增供应商
                </Button>
              </Space>
            </div>

            <Table
              columns={supplierColumns}
              dataSource={supplierList}
              loading={loading}
              rowKey="id"
              pagination={{
                total: supplierList.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </TabPane>

          <TabPane tab="分类管理" key="categories">
            <div style={{ marginBottom: 16 }}>
              <Space>
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAddCategory}>
                  新增分类
                </Button>
              </Space>
            </div>

            <Table
              columns={categoryColumns}
              dataSource={categories}
              loading={loading}
              rowKey="id"
              pagination={{
                total: categories.length,
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={editingRecord ? '编辑供应商' : '新增供应商'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmitSupplier}
        >
          <Form.Item
            name="name"
            label="供应商名称"
            rules={[{ required: true, message: '请输入供应商名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="contact"
            label="联系人"
            rules={[{ required: true, message: '请输入联系人' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="phone"
            label="电话"
            rules={[{ required: true, message: '请输入电话' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select>
              {categories.map(category => (
                <Option key={category.id} value={category.name}>{category.name}</Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="address"
            label="地址"
          >
            <TextArea rows={3} />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={editingCategory ? '编辑分类' : '新增分类'}
        open={categoryModalVisible}
        onCancel={() => setCategoryModalVisible(false)}
        onOk={() => categoryForm.submit()}
        width={400}
      >
        <Form
          form={categoryForm}
          layout="vertical"
          onFinish={handleSubmitCategory}
        >
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
